﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using LightXiuCore;
namespace XiuXiuTools
{
    public partial class ExportDataForm : XiuXiuTools.BaseForm
    {
        public event EventHandler CalBackClick;

        /// <summary>
        /// 用户类别列表
        /// </summary>
        DataTable UserTypeList = new DataTable();
        DataTable TimeData = new DataTable();
        public ExportDataForm()
        {
            InitializeComponent();
        }

      
        /// <summary>
        /// 选择模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            var dlg = tempOpenFileDialog.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                txtTjName.Text = tempOpenFileDialog.FileName;
            }
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            SetControlsEnable(this, false);
            backgroundLoad.RunWorkerAsync("saveconfig");
        }
        /// <summary>
        /// 导出按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            resSaveFileDialog.FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            var dlg = resSaveFileDialog.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                SetControlsEnable(this, false);
                var obj = (cmbUserType.SelectedItem as DataRowView).Row;
                var parms = new string[] { obj["EMP_TYPE_NAME"].ToString(), cmbTime.Text, txtTjName.Text, obj["M_START_ROW"].ToString(), obj["T_START_COUNT"].ToString(), obj["M_START_COL"].ToString(), obj["M_START_SELF"].ToString(), resSaveFileDialog.FileName};
                backgroundWorker1.RunWorkerAsync(parms);
            }
        }
        private LightXiuCore.LightData.XIU_EMPDataTable GetUserList(string userType)
        {

            var dt = new LightXiuCore.LightData.XIU_EMPDataTable();
            var dtU = serviceClient.GetDataBySql("SELECT * FROM  zjwdb_165769.xiu_emp WHERE  EMP_TYPE =  '" + userType + "';", "users");
            foreach (DataRow  row in dtU.Rows)
            {
                dt.Rows.Add(row.ItemArray);
            }
            return dt;
        }

        private LightXiuCore.LightData.XIU_EMP_SCOREDataTable GetScoreList(string timeType)
        {

            var dt = new LightXiuCore.LightData.XIU_EMP_SCOREDataTable();
            var dtU = serviceClient.GetDataBySql("SELECT * FROM  zjwdb_165769.xiu_emp_score WHERE  SCROE_TIME =  '" + timeType + "';", "users");
            foreach (DataRow row in dtU.Rows)
            {
                dt.Rows.Add(row.ItemArray);
            }
            return dt;
        }

        /// <summary>
        /// 导出结果
        /// </summary>
        private string DoExportDataForm(string userType, string timeType, string tempFile, int MBrowData, int MBallCout, int MBcolData, int MBselfData,string saveFile)
        {
            if (txtTjName.Text == "")
            {
                MessageBox.Show("请选择模板!");
                return "";
            }
            try
            {
         
   
                var file = new FileInfo(tempFile);
                var hssfworkbook = new OfficeOpenXml.ExcelPackage(file);
                var book = hssfworkbook.Workbook;
                book.CalcMode = OfficeOpenXml.ExcelCalcMode.AutomaticNoTable;

                var dt = GetUserList(userType);
                var dtscore = GetScoreList(timeType);
                var sheet = book.Worksheets.Where(wh => wh.Name == "评价模板");
              
                if (sheet.Count() < 0)
                {
                    MessageBox.Show("模板文件错误!");
                    return "";
                }


                foreach (LightXiuCore.LightData.XIU_EMPRow userInfo in dt.Rows)
                {
                    var rows = dtscore.Count(wh => wh.SCROE_OWNER_EMP_NAME == userInfo.EMP_NAME && wh.SCROE_VALUE > 0);
                    if (rows > 0)
                    {
                        var sheetCur = book.Worksheets.Copy("评价模板", userInfo.EMP_NAME);
                        
                        int rowStart = MBrowData;
                        while (rowStart < MBrowData + MBallCout)
                        {
                            var valObj = sheetCur.Cells[rowStart, MBcolData];
                            var strItemName = (valObj == null || valObj.Value == null ? "" : valObj.Value.ToString());
                            var self = dtscore.FirstOrDefault(wh => wh.SCROE_OWNER_EMP_NAME == userInfo.EMP_NAME && wh.SCROE_EMP_NAME == userInfo.EMP_NAME && wh.SCROE_TYPE == strItemName);

                            if (self != null)
                            {

                                var celSelf = sheetCur.Cells[rowStart, MBselfData];
                                celSelf.Value = self.SCROE_VALUE;
                            }
                            var colStart = MBselfData + 1;

                            var UserObj = sheetCur.Cells[MBrowData - 1, colStart];
                            var destUser = (UserObj == null || UserObj.Value == null ? "" : UserObj.Value.ToString());
                            while (!string.IsNullOrEmpty(destUser))
                            {
                                var selfRow = dtscore.FirstOrDefault(wh => wh.SCROE_OWNER_EMP_NAME == userInfo.EMP_NAME && wh.SCROE_EMP_NAME == destUser && wh.SCROE_TYPE == strItemName);
                                if (selfRow != null && destUser != userInfo.EMP_NAME && selfRow.SCROE_VALUE > 0)
                                {
                                    var celScore = sheetCur.Cells[rowStart, colStart];

                                    celScore.Value = selfRow.SCROE_VALUE;
                                }

                                colStart++;
                                UserObj = sheetCur.Cells[MBrowData - 1, colStart];
                                destUser = (UserObj == null || UserObj.Value == null ? "" : UserObj.Value.ToString());
                            }
                            var strUserNameUserObj = sheetCur.Cells[rowStart, MBselfData];

                            var strUserName = (strUserNameUserObj == null || strUserNameUserObj.Value == null ? "" : strUserNameUserObj.Value.ToString());

                            rowStart++;
                        }
                    }
                    else
                    {
                        MessageBox.Show(userInfo.EMP_NAME + "没有找到评价数据");
                        continue;
                    }
                }

                book.Worksheets.Delete("评价模板");
                var fileNew = new FileInfo(saveFile);
                hssfworkbook.SaveAs(fileNew);
              
                return saveFile;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                WriteLog.WriteLogs(ex.Message + "\r\n" + ex.StackTrace);
                return "";
            }
        }
        /// <summary>
        /// 开始处理后台操作代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundLoad_DoWork(object sender, DoWorkEventArgs e)
        {
            var arg = e.Argument as string;
            if (arg != null)
            {
                if (arg == "load")
                {
                    UserTypeList = serviceClient.GetDataBySql("SELECT * FROM zjwdb_165769.xiu_emp_type;", "userType");
                    TimeData = serviceClient.GetDataBySql("SELECT DISTINCT SCROE_TIME FROM  zjwdb_165769.xiu_emp_score; ", "timeData");

                }
                if (arg == "saveconfig")
                {
                    serviceClient.UpdateData(cmbUserType.DataSource as DataTable, "SELECT * FROM zjwdb_165769.xiu_emp_type where 1=2 ;", "");

                }
            }

        }

        /// <summary>
        /// 文本改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtRowData_TextChanged(object sender, EventArgs e)
        {
            var sd = sender as TextBox;
            var obj = (cmbUserType.SelectedItem as DataRowView).Row;
            if (obj != null)
            {
                obj[sd.Tag.ToString()] = sd.Text;
            }
        }
        /// <summary>
        /// 用户类别选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var obj = (cmbUserType.SelectedItem as DataRowView).Row;
            if (obj != null)
            {
                txtRowData.Text = obj["M_START_ROW"].ToString();
                txtRowData.Tag = "M_START_ROW";
                txtColData.Text = obj["M_START_COL"].ToString();
                txtColData.Tag = "M_START_COL";

                txtSelfData.Text = obj["M_START_SELF"].ToString();
                txtSelfData.Tag = "M_START_SELF";
            }
        }
        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExportDataForm_Load(object sender, EventArgs e)
        {
           
            SetControlsEnable(this, false);
            backgroundLoad.RunWorkerAsync("load");
            cmbUserType.SelectedIndexChanged += new EventHandler(cmbUserType_SelectedIndexChanged);
        }

        /// <summary>
        /// 加载数据完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundLoad_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          
            SetControlsEnable(this, true);
            txtTjName.Enabled = false;
            cmbUserType.DataSource = UserTypeList;
            cmbUserType.DisplayMember = "EMP_TYPE_NAME";
            cmbUserType.ValueMember = "EMP_TYPE_ID";
            cmbTime.DataSource = TimeData;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var parms = e.Argument as string[];
            if (parms!=null)
            {
                e.Result = DoExportDataForm(parms[0], parms[1], parms[2], int.Parse(parms[3]), int.Parse(parms[4]), int.Parse(parms[5]), int.Parse(parms[6]), parms[7]);
            }
           
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            SetControlsEnable(this, true);
            if (CalBackClick!=null)
            {
                CalBackClick(e.Result, e);
            }
            txtTjName.Enabled = false;
        }
    }
}
